package com.help10000.rms.ui.activitys.mine.address

import android.os.Bundle
import android.view.View
import com.amir.common.beans.AddressItem
import com.amir.common.beans.DefaultCityItem
import com.amir.common.beans.Zone
import com.amir.common.beans.ZoneEntity
import com.amir.common.utils.PermissionUtils
import com.amir.common.utils.ToastUtil
import com.amir.common.weight.DuplicateClickProxy
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.help10000.rms.R
import com.help10000.rms.mvp.presenter.EditAddressPresenter
import com.help10000.rms.mvp.view.AddressEditView
import com.help10000.rms.ui.base.BaseActivity
import com.help10000.rms.utils.LocationManager
import kotlinx.android.synthetic.main.activity_add_address.*

class AddAddressActivity : BaseActivity<EditAddressPresenter, AddressEditView>(), AddressEditView,
    View.OnClickListener {
    var provinces = mutableListOf<Zone>()
    var citys = mutableListOf<MutableList<Zone>>()
    var towns = mutableListOf<MutableList<MutableList<Zone>>>()
    var defaultCityItem: DefaultCityItem? = null
    var province: Zone? = null
    var city: Zone? = null
    var town: Zone? = null
    var addressItem: AddressItem? = null

    override fun getlayoutId(): Int {
        return R.layout.activity_add_address
    }

    override fun initView() {

    }

    override fun onSaveInstanceState(outState: Bundle) {
        outState.putSerializable("address", addressItem)
        super.onSaveInstanceState(outState)
    }

    override fun initData(savedInstanceState: Bundle?) {
        if (savedInstanceState != null) {
            addressItem = savedInstanceState.getSerializable("address") as AddressItem?
        } else {
            addressItem = intent.getSerializableExtra("address") as AddressItem?
        }
        if (addressItem == null) {
            mPresenter.init()
        } else {
            defaultCityItem =
                DefaultCityItem(addressItem!!.ProvID, addressItem!!.CityID, addressItem!!.TownID)
            Address.text = addressItem?.ProvName + addressItem?.CityName + addressItem?.TownName
            et_zone.setText(addressItem?.Zone5)
            et_phone.setText(addressItem?.Mobile)
            et_contact.setText(addressItem?.ContactName)
            titleBar.setTitle("修改地址")
            btnSave.text = "保存"
        }
        mPresenter.getZoneInfo()
    }


    override fun initListener() {
        Address.setOnClickListener(DuplicateClickProxy(this))
        btnAddress.setOnClickListener(DuplicateClickProxy(this))
        btnSave.setOnClickListener(DuplicateClickProxy(this))

    }

    override fun createPresenter(): EditAddressPresenter {
        return EditAddressPresenter(this)
    }


    override fun initSuccess(data: DefaultCityItem?) {
        this.defaultCityItem = data

    }

    override fun onZoneDataSuccess(data: ZoneEntity) {
        initZoneData(data)
    }

    override fun onError(mess: String?) {
        super.onError(mess)
        btnSave.isEnabled = true
    }

    override fun onSuccess() {
        btnSave.isEnabled = true // 恢复按钮（即使即将关闭页面，避免特殊情况）
        if (addressItem != null) {
            ToastUtil.show("修改成功")
        } else
            ToastUtil.show("添加成功")
        finish()
    }
    // 新增：处理协程取消或页面销毁时的状态恢复
    override fun onDestroy() {
        super.onDestroy()
        btnSave.isEnabled = true // 页面销毁前确保按钮状态正常
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btnSave -> {
                var contact = et_contact.text.toString()
                if (contact.isNullOrEmpty()) {
                    ToastUtil.show("请输入联系人")
                    return
                }
                var tel = et_phone.text.toString()
                if (tel.isNullOrEmpty()) {
                    ToastUtil.show("请输入电话")
                    return
                }
                if (province == null && addressItem == null) {
                    ToastUtil.show("请选择地区")
                    return
                }
                var zone = et_zone.text.toString()
                if (zone.isNullOrEmpty()) {
                    ToastUtil.show("请输入详细地址")
                    return
                }
                btnSave.isEnabled = false
                if (addressItem == null) {
                    mPresenter.addAddress(
                        tel,
                        contact,
                        province!!.id,
                        city!!.id,
                        town!!.id,
                        zone,
                        activity = this
                    )
                } else {
                    mPresenter.editAddress(
                        addressItem!!.AddrId,
                        tel,
                        contact,
                        addressItem!!.ProvID,
                        addressItem!!.CityID,
                        addressItem!!.TownID,
                        zone,
                        activity = this
                    )
                }
            }
            R.id.Address,
            R.id.btnAddress -> {
                var optionPickerView = OptionsPickerBuilder(
                    this,
                    object : OnOptionsSelectListener {
                        override fun onOptionsSelect(
                            options1: Int,
                            options2: Int,
                            options3: Int,
                            v: View?
                        ) {
                            province = provinces[options1]
                            city = citys[options1][options2]
                            town = towns[options1][options2][options3]
                            Address.text = province!!.name + city!!.name + town!!.name
                            if (addressItem != null) {
                                addressItem!!.ProvID = province!!.id
                                addressItem!!.CityID = city!!.id
                                addressItem!!.TownID = town!!.id

                            }
                        }
                    }).setTitleText("选择地区")
                    .build<Zone>()

                optionPickerView.setPicker(provinces, citys, towns)
                var provinceIndex = 0
                var cityIndex = 0
                var zoneIndex = 0
                if (defaultCityItem != null) {
                    for (index in provinces.indices) {
                        if (provinces[index].id == defaultCityItem!!.DefaultProvId) {
                            provinceIndex = index
                            break
                        }
                    }
                    for (index in citys[provinceIndex].indices) {
                        if (citys[provinceIndex][index].id == defaultCityItem!!.DefaultCityId) {
                            cityIndex = index
                            break
                        }
                    }
                    for (index in towns[provinceIndex][cityIndex].indices) {
                        if (towns[provinceIndex][cityIndex][index].id == defaultCityItem!!.DefaultTownId) {
                            zoneIndex = index
                            break
                        }
                    }
                }
                optionPickerView.setSelectOptions(
                    provinceIndex,
                    cityIndex,
                    zoneIndex
                )
                optionPickerView.show()
            }

        }
    }


    fun initZoneData(data: ZoneEntity) {
        for (province in data.data) {
            provinces.add(Zone(province.id, province.name))
            var subCitys = mutableListOf<Zone>()
            var subTones = mutableListOf<MutableList<Zone>>()
            for (city in province.citys) {
                subCitys.add(Zone(city.id, city.name))
                var tones = mutableListOf<Zone>()
                for (town in city.towns) {
                    tones.add(Zone(town.id, town.name))
                }
                subTones.add(tones)
            }
            towns.add(subTones)
            citys.add(subCitys)

        }
        var provinceIndex = 0
        var cityIndex = 0;
        var text = ""
        if (defaultCityItem != null) {
            for (index in provinces.indices) {
                if (provinces[index].id == defaultCityItem!!.DefaultProvId) {
                    provinceIndex = index
                    text += provinces[index].name
                    province = provinces[index]
                    break
                }
            }
            for (index in citys[provinceIndex].indices) {
                if (citys[provinceIndex][index].id == defaultCityItem!!.DefaultCityId) {
                    cityIndex = index
                    city = citys[provinceIndex][index]
                    text += citys[provinceIndex][index].name
                    break
                }
            }
            for (index in towns[provinceIndex][cityIndex].indices) {
                if (towns[provinceIndex][cityIndex][index].id == defaultCityItem!!.DefaultTownId) {
                    text += towns[provinceIndex][cityIndex][index].name
                    town = towns[provinceIndex][cityIndex][index]
                    break
                }
            }
        }
        Address.text = text

    }
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PermissionUtils.REQUEST_LOCATION) {
            // 无论权限是否授予，都恢复按钮状态（避免长期禁用）
            btnSave.isEnabled = true
            // 继续处理权限结果（交给 LocationManager）
            LocationManager.onRequestPermissionsResult(grantResults, permissions)
        }
    }
}